package com.zhiwang.planet.ui

import android.Manifest.permission.*
import android.content.Intent
import android.content.pm.PackageManager
import android.graphics.drawable.ColorDrawable
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.provider.Settings
import androidx.core.app.ActivityCompat
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity
import android.util.Log
import android.view.View
import android.view.WindowManager
import com.bytedance.sdk.openadsdk.*
import com.zhiwang.planet.BuildConfig
import com.zhiwang.planet.R
import com.zhiwang.planet.util.quickStartActivity
import com.zhiwang.planet.util.suicideAfterTransition
import kotlinx.android.synthetic.main.activity_splash.*
import kotlinx.android.synthetic.main.permission_layout.view.*


class SplashActivity : AppCompatActivity() {

    //storage
    val storagePermission = arrayOf(WRITE_EXTERNAL_STORAGE, READ_EXTERNAL_STORAGE)

    val phonePermission = arrayOf(READ_PHONE_STATE)

    val wifiPermission = arrayOf(ACCESS_WIFI_STATE)

    val allPermission = arrayOf(WRITE_EXTERNAL_STORAGE, READ_EXTERNAL_STORAGE, READ_PHONE_STATE)

    var storagePermitted = false

    var phonePermitted = false

    var wifiPermitted = false

    var dialog: AlertDialog? = null

    var appSettingDialog: AlertDialog? = null

    var visibleTime = 0L

    val TAG = "SplashActivity"

    var adHasClicked = false

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_splash)
//        Utils.setStatusBar(this, false, false)
        val uiOptions = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION or View.SYSTEM_UI_FLAG_FULLSCREEN
        val uiOptions4 = (View.SYSTEM_UI_FLAG_FULLSCREEN
                or View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                or View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                or View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                or View.SYSTEM_UI_FLAG_LAYOUT_STABLE)
        window.decorView.systemUiVisibility = uiOptions4
        if (supportActionBar != null)
            supportActionBar!!.hide()
        val lp = window.attributes

        //针对水滴屏（刘海屏）的全屏处理
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
            lp.layoutInDisplayCutoutMode = WindowManager.LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_SHORT_EDGES
        }
        //设置页面延伸到刘海区显示
        window.attributes = lp
        this.window.setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN)

        if (checkPermissions())//如果已经有权限了，加载广告，否则只走申请广告然后 跳转首页的逻辑
//            requestSplashAd()

        else {
            processPermission()
        }
    }

    private lateinit var ttAdManager: TTAdManager

    private fun requestSplashAd() {

        val width = resources.displayMetrics.widthPixels
        val height = resources.displayMetrics.heightPixels

        val adSlot = AdSlot.Builder()
                .setCodeId("831608960")
                .setSupportDeepLink(true)
                .setImageAcceptedSize(width, height)
                .build()


        ttAdManager = TTAdSdk.getAdManager()

        ttAdManager.requestPermissionIfNecessary(this)
        ttAdManager.createAdNative(this)
                .loadSplashAd(adSlot, object : TTAdNative.SplashAdListener {
                    override fun onSplashAdLoad(ad: TTSplashAd?) {
                        if (ad == null || !window.isActive)
                            return
                        splashAdContainer.addView(ad.splashView)

                        ad.setSplashInteractionListener(object : TTSplashAd.AdInteractionListener {

                            override fun onAdClicked(p0: View?, p1: Int) {
                                adHasClicked = true
                                window.decorView.removeCallbacks(goMainPageRunnable)
                            }

                            override fun onAdSkip() {
                                goMainPageRunnable.run()
                                window.decorView.removeCallbacks(goMainPageRunnable)
                            }

                            override fun onAdShow(p0: View?, p1: Int) {

                            }

                            override fun onAdTimeOver() {
                                goMainPageRunnable.run()
                            }

                        })

                    }

                    override fun onTimeout() {
                        goMainPageRunnable.run()

                    }

                    override fun onError(p0: Int, p1: String?) {
                        goMainPageRunnable.run()

                    }

                })


    }

    override fun onStart() {
        super.onStart()
        super.onResume()
        visibleTime = System.currentTimeMillis()
        //默认走一遍申请权限的流程
        if (requestInAppSetting.not())
            ActivityCompat.requestPermissions(this, allPermission, 112)

        if (adHasClicked)
            goMainPageRunnable.run()
    }

    override fun onPause() {
        super.onPause()
        dialog?.dismiss()
        appSettingDialog?.dismiss()
    }


    private fun processPermission() {
        if (checkPermissions()) {
            Handler(Looper.getMainLooper()).postDelayed({
                nextPage()
                suicideAfterTransition()
            }, 1314)
        } else {
            //弹出权限申请提示窗口
            showMissingPermissionDialog()
        }
    }

    private fun checkPermissions(): Boolean {
        //storage
        if (ActivityCompat.checkSelfPermission(this, WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {

        } else {
            storagePermitted = true
        }

        //phone
        if (ActivityCompat.checkSelfPermission(this, READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {

        } else {
            phonePermitted = true
        }

        if (ActivityCompat.checkSelfPermission(this, ACCESS_WIFI_STATE) != PackageManager.PERMISSION_GRANTED) {

        } else
            wifiPermitted = true
        return storagePermitted && phonePermitted && wifiPermitted
    }

    private fun showMissingPermissionDialog() {

        //如果每个权限都是被禁止了，并且不再询问，那么提示去应用管理中授予权限
        allPermission.forEach {
            if (ActivityCompat.shouldShowRequestPermissionRationale(this@SplashActivity, it)) {
                val permissionView = layoutInflater.inflate(R.layout.permission_layout, null)
                permissionView.next_step.setOnClickListener {
                    requestMissingPermission()
                    dialog?.dismiss()
                }

                dialog = AlertDialog.Builder(this, R.style.LargeAlertDialogStyle)
                        .setView(permissionView)
                        .setCancelable(false)
                        .create()
                dialog
                        ?.show()
                return
            }
        }

        requestPermissionInAppSetting()
    }

    private fun requestMissingPermission() {

        var permissionGroup = arrayListOf<String>()

        if (storagePermitted.not()) permissionGroup.addAll(storagePermission)
        if (phonePermitted.not()) permissionGroup.addAll(phonePermission)
        if (wifiPermitted.not()) permissionGroup.addAll(wifiPermission)


        //如果有一个权限可以showRationale，则再次请求所有权限，反之弹窗提示去应用管理中授予权限，如果依然拒绝，停留在该页面
        val list: List<String> = permissionGroup.filter {
            ActivityCompat.shouldShowRequestPermissionRationale(this@SplashActivity, it)
        }

        if (list.isNotEmpty()) {
            ActivityCompat.requestPermissions(this, list.toTypedArray(), 112)
        } else

        //全部都是禁止不再询问，那么弹窗提示去设置
            requestPermissionInAppSetting()
    }


    var requestInAppSetting = false
    private fun requestPermissionInAppSetting() {
        requestInAppSetting = true
        appSettingDialog = AlertDialog.Builder(this@SplashActivity, R.style.LargeAlertDialogStyle)
                .setTitle("权限不足")
                .setMessage("没有足够权限,趣味星球无法正常运行，请开启权限后再使用。\n\n" +
                        "设置路径:应用管理-> 趣味星球->权限")
                .setCancelable(false)
                .setOnDismissListener {
                    requestInAppSetting = false
                }
                .setNegativeButton("拒绝") { dialog, which ->
                    dialog.dismiss()
                }
                .setPositiveButton("去设置") { dialog, which ->
                    val intent = Intent()
                    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
                    intent.action = Settings.ACTION_APPLICATION_DETAILS_SETTINGS
                    intent.data = Uri.parse("package:$packageName")
                    startActivity(intent)
                    dialog.dismiss()
                }
                .create()

        appSettingDialog?.window?.setBackgroundDrawable(ColorDrawable(android.graphics.Color.WHITE))
        val lp = WindowManager.LayoutParams()
        val attributes = appSettingDialog?.window?.attributes
        lp.copyFrom(attributes)

        lp.width = (resources.displayMetrics.widthPixels * 0.92).toInt()
        lp.height = WindowManager.LayoutParams.WRAP_CONTENT
        appSettingDialog?.window?.attributes = lp
        appSettingDialog?.show()
    }

    override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        if (permissions.isEmpty() || grantResults.isEmpty()) return
        if (requestCode == 112) {
            if (checkPermissions()) {
                nextPage()
            } else {
                requestMissingPermission()
            }
        }
    }

    var jumped = false

    val goMainPageRunnable = Runnable {

        quickStartActivity(MainActivity::class.java)
        suicideAfterTransition()
    }


    private fun nextPage() {
        Log.i(TAG, "nextPage: ------")
        if (jumped) return
        jumped = true
        //有可能申请了权限过程花费了时间，此时至少停留一秒
        window.decorView.postDelayed(goMainPageRunnable, Math.max(2000, System.currentTimeMillis() - visibleTime))
    }


    override fun onDestroy() {
        super.onDestroy()
        if (::ttAdManager.isInitialized) {

        }
        window.decorView.removeCallbacks(goMainPageRunnable)
    }
}
